//
//  CZHomeViewController.swift
//  iOSWeibo10
//
//  Created by itcast on 16/5/9.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVPullToRefresh


class CZHomeViewController: CZBaseTableViewController {

    private let reuserIdentifier = "cell"
    
    var statuses: [CZStatus]?{
        didSet{
            self.tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if !CZUserAccountViewModel.sharedInstance.isUserLogin{
            return
        }
        setupNavigationBar()
        prepareTableView()
        navigationController?.navigationBar.insertSubview(tipLabel, atIndex: 0)
    }
    
    private func prepareTableView(){
        tableView.registerClass(CZStatusCell.self, forCellReuseIdentifier: reuserIdentifier)
//        tableView.estimatedRowHeight = 200
        tableView.rowHeight = UITableViewAutomaticDimension
        
        tableView.addSubview(pullDownToRefreshControl)
        
        pullDownToRefreshControl.pullDownToRefreshCallback = {
            () -> () in
            self.loadNewStatus()
        }
        pullDownToRefreshControl.beginRefreshing()
        
        tableView.addInfiniteScrollingWithActionHandler { () -> Void in
             self.loadMoreStatus()
        }
    }
    
    private func loadMoreStatus(){
        let max_id = self.statuses?.last?.id ?? 0
        CZStatusViewModel.sharedInstance.loadStatus(0, max_id: max_id) { (statuses, error) -> () in
            self.tableView.infiniteScrollingView.stopAnimating()
            
            if error != nil{
                CZPrint(items: "上拉加载微博出错了: \(error)")
                return
            }
            
            let count = statuses?.count ?? 0
            if count == 0{
                CZPrint(items: "上拉没有加载到微博数据")
                return
            }
            // 将获取到的微博数据添加到现有数据的后面
             self.statuses = self.statuses! + statuses!
        }
    }
    
    private func loadNewStatus(){
        let since_id = self.statuses?.first?.id ?? 0
        CZStatusViewModel.sharedInstance.loadStatus(since_id, max_id: 0) { (statuses, error) -> () in
            self.pullDownToRefreshControl.endRefreshing()
            if error != nil{
                CZPrint(items: "加载微博出错了: \(error)")
                return
            }
            
            let count = statuses?.count ?? 0
            
            if since_id > 0{
                self.showTipLabel(count)
            }
            
            if count == 0{
                return
            }
            
            if since_id == 0{
                self.statuses = statuses
            }else{
                self.statuses = statuses! + self.statuses!
            }
        }
    }
    
    private func showTipLabel(count: Int){
        let text = count == 0 ? "没有新的微博" : "加载了 \(count) 条新微博"
        tipLabel.text = text
        let animation = self.tipLabel.layer.animationKeys()
        if animation != nil{
             CZPrint(items: "之前有动画没做完,移除: \(animation)")
            self.tipLabel.layer.removeAllAnimations()
        }
        let duration = 0.75
        UIView.animateWithDuration(duration, animations: { () -> Void in
            self.tipLabel.frame.origin.y = 44
            }) { (_) -> Void in
                UIView.animateWithDuration(duration, delay: 1, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
                    self.tipLabel.frame.origin.y = -64
                    }, completion: nil)
        }
    }

    private func  setupNavigationBar(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", target: self, action: "didClickFriendsearch")
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: "didClickPop")
        let button = CZHomeTitleButton()
        let name = CZUserAccountViewModel.sharedInstance.userAccount?.screen_name ?? "未知名称"
        button.setTitle(name, forState: UIControlState.Normal)
        button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
        button.titleLabel?.font = UIFont.systemFontOfSize(16)
         button.setImage(UIImage(named: "navigationbar_arrow_down"), forState: UIControlState.Normal)
        button.addTarget(self, action: "didClickTitlView:", forControlEvents: UIControlEvents.TouchUpInside)
        button.sizeToFit()
        navigationItem.titleView = button
    }
    func didClickTitlView(button: CZHomeTitleButton){
        button.selected = !button.selected
        UIView.animateWithDuration(0.25) { () -> Void in
            let tranform = button.selected ? CGAffineTransformMakeRotation(CGFloat(M_PI - 0.001)) : CGAffineTransformIdentity
            button.imageView?.transform = tranform
        }
    }
    
    func didClickFriendsearch() {
        CZPrint(items: "点击了左边")
    }
    
    func didClickPop() {
        CZPrint(items: "点击了右边")
    }
    
    private lazy var pullDownToRefreshControl: CZPullDownToRefreshControl = CZPullDownToRefreshControl()
    
    private lazy var tipLabel: UILabel = {
       let label = UILabel()
        label.backgroundColor = UIColor.orangeColor()
        label.font = UIFont.systemFontOfSize(18)
        label.textColor = UIColor.whiteColor()
        label.textAlignment = NSTextAlignment.Center
        
        label.frame = CGRect(x: 0, y: -64, width: UIScreen.mainScreen().bounds.width, height: 44)
        return label
    }()
}

extension CZHomeViewController{
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let status = self.statuses![indexPath.row]
        if let rowHeight = status.rowHeight{
            return rowHeight
        }
        
        let cell = tableView.dequeueReusableCellWithIdentifier(reuserIdentifier) as! CZStatusCell
        cell.status = status
        let rowHeight = cell.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
        status.rowHeight = rowHeight
        return rowHeight
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(reuserIdentifier, forIndexPath: indexPath) as! CZStatusCell
        let status = self.statuses![indexPath.row]
//        cell.textLabel?.text = status.text
        cell.status = status
        return cell
    }
}
